define [
  'views/base/view'
  'jquery.ui.widget'
  'jquery.fileupload'
  'jquery.iframe-transport'
  'text!templates/base/file.html'
], ->

  'use strict'

  # Imports
  # =============================================================

  BaseView = require 'views/base/view'
  Template = require 'text!templates/base/file.html'

  class FileView extends BaseView

    # Override Attributes
    # =============================================================

    template  : Template
    className : 'cadastro-file'
    events:
      'click .file-remove' : 'clickFileRemoveHandler'

    # Override Attributes
    # =============================================================

    # Override Methods
    # =============================================================
    initialize: ->
      super

      @label     or= 'Label do arquivo'
      @fileId    or= 'input-' + @cid

      # URL de upload dos arquivos
      @uploadUrl or= window.AppData.API_URL + '/upload'

      # URL dos arquivos temporários
      @imagePath or= window.AppData.API_URL + '/arquivo/'

      # Tamanho máximo do arquivo
      @maxSize or= 3000000

      # Regex de tipos aceitáveis de arquivos
      @acceptFilesRegex or= /(\.|\/)(shp|dbf|shx|kml)$/i

      @acceptFileArray or= ['.shp', '.dbf', '.shx', '.kml']

      @render()

    getTemplateData: ->
      _.extend super,
        label     : @label
        fileId    : @fileId
        fileTypes : @acceptFileArray.join ','

    afterRender: ->
      super
      @setupFileInput()

    cacheDOMElements: ->
      _.extend super,
        $formGroup       : @$ '.form-group'
        $fileInput       : @$ '#' + @fileId
        $inputGroup      : @$ '.input-group'
        $fileLink        : @$ '.file-link'
        $loaderContainer : @$ '.loader-container'
        $loaderColumn    : @$ '.loader-column'

    # Additional Methods
    # =============================================================

    setupFileInput: (options={})->
      defaultOptions =
        dataType                 : 'text'
        url                      : @uploadUrl
        forceIframeTransport     : true
        limitMultiFileUploadSize : @maxSize
        acceptFileTypes          : @acceptFilesRegex
        fail : => @publishEvent 'feedback:error', 'upload.erro'
        add  : (event, data) =>
          @closeTooltips()
          data.files = _.filter data.files, (f) => @acceptFilesRegex.test f.name

          file = data.files[0] if data.files.length

          # Erro de tipo de arquivo
          if !file
            @publishEvent 'feedback:error', 'upload.erro.tipo'
            return

          # Erro de tamanho de arquivo
          if file.size and file.size > @maxSize
            @publishEvent 'feedback:error', 'upload.erro.tamanho'
            return

          # Nome do arquivo
          @setLinkText file.name

          # Exibição do load
          @showLoader()

          # Envio do arquivo para o Backend
          data.submit()
        done: (event, data) => @setFileSrc data.result

      @DOMElements.$fileInput.fileupload _.extend defaultOptions, options

    showLoader: ->
      @DOMElements.$inputGroup      .addClass    'hide'
      @DOMElements.$loaderColumn    .removeClass 'hide'
      @DOMElements.$loaderContainer .removeClass 'hide'

    hideLoader: ->
      @DOMElements.$formGroup       .removeClass 'has-success .has-error'
      @DOMElements.$loaderContainer .addClass    'hide'
      @DOMElements.$inputGroup      .removeClass 'hide'
      @DOMElements.$loaderColumn    .removeClass 'hide'
      @DOMElements.$fileLink        .attr('href', '').text ''

    setLinkText: (text) ->
      return unless text
      @DOMElements.$fileLink.text text

    setFileSrc: (fileName) ->
      return unless fileName
      @setLinkText fileName unless @DOMElements.$fileLink.text()

      path = @imagePath

      @DOMElements.$fileLink     .attr     'href', path + fileName
      @showLoader()
      @DOMElements.$loaderColumn .addClass 'hide'

      @fileName = fileName
      @trigger 'file:edited', @fileName

      return @fileName

    removeFile: ->
      @hideLoader()

      @fileName = null
      @trigger 'file:removed'

    getFileName: ->
      return @fileName

    # Event Handlers
    # =============================================================
    clickFileRemoveHandler: (event) ->
      event.preventDefault()
      @removeFile()

